<template>
	<view class="content">
		<u-button v-if="photopeny" @click="addressAgain" bindopensetting="addressAgain"> 手动获取相册权限</u-button>
		<canvas canvas-id="myCanvas" style="width: 750rpx; height: 750rpx;position: absolute;left:1000000px"></canvas>

		<cropper selWidth="750rpx" selHeight="750rpx" @upload="myUpload"
			avatarSrc="https://img2.baidu.com/it/u=2788034579,3700791329&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
			avatarStyle="width:750rpx;height:750rpx;">
		</cropper>
		<u-button @click="onSaveAllwx" v-if="imgsrc && imgsrc.length===9">全部保存</u-button>
		<u-steps :current="Number(currentLength.length)"  v-if="imgsrc && imgsrc.length===9">
			<u-steps-item :title="`图${index+1}`" v-for="(i,index) in imgsrc" :key="index"></u-steps-item>
		</u-steps>
		<view class="content" style="display: flex;flex-direction: row;flex-wrap:wrap;width:100%">
			<view v-for="i in imgsrc" :key="i"
				style="min-width:245rpx;max-width:245rpx;height:245rpx;max-height:245rpx;border:1px solid black">
				<img style="width:100%;height:100%" :src="i" alt="">
			</view>
		</view>
	</view>
</template>

<script>
	import cropper from "../../components/lxiaoxiao-cropper/lxiaoxiao-cropper.vue";
	export default {
		components: {
			cropper
		},
		data() {
			return {
				imgsrc: [],
				fileList1: [],
				photopeny: false,
				currentLength:[]
			}
		},
		mounted() {},
		onLoad() {

		},
		methods: {
			//上传返回图片
			myUpload(rsp) {
				const self = this;
				console.log(rsp.path)
				// self.imgurl = rsp.path; //更新头像方式一
				this.splitImageIntoBase64wx(rsp.path);
			},
			// h5的点击下载
			saveBase64Image(base64, fileName) {
				// 创建一个a元素用于触发下载
				const link = document.createElement('a');
				link.style.display = 'none'; // 隐藏链接
				link.href = base64; // 将Base64字符串设置为下载链接
				link.download = fileName; // 设置下载文件名

				// 将a元素添加到文档中，并模拟点击
				document.body.appendChild(link);
				link.click();
				// 移除a元素
				document.body.removeChild(link);
			},

			splitImageIntoBase64(imageUrl, callback) {
				const img = new Image();
				img.crossOrigin = 'Anonymous'; // 如果图片需要跨域访问，可能需要设置这个属性
				img.onload = function() {
					const canvas = document.createElement('canvas');
					const ctx = canvas.getContext('2d');
					const tileSize = Math.ceil(img.width / 3.01); // 假设切割成3x3九宫格

					const base64Images = [];
					for (let row = 0; row < 3; row++) {
						for (let col = 0; col < 3; col++) {
							canvas.width = tileSize;
							canvas.height = tileSize;
							ctx.drawImage(img, col * tileSize, row * tileSize, tileSize, tileSize, 0, 0, tileSize,
								tileSize);
							const base64Image = canvas.toDataURL('image/jpeg'); // 或者 'image/png' 如果你需要PNG格式
							base64Images.push(base64Image);
						}
					}

					callback(base64Images); // 使用回调函数返回所有的Base64字符串
				};
				img.src = imageUrl;
			},


			splitImageIntoBase64wx(imageUrl) {
				return new Promise((resolve, reject) => {
					wx.getImageInfo({
						src: imageUrl,
						success: (imageInfo) => {
							const {
								width,
								height
							} = imageInfo;
							// 假设图片是正方形的，或者至少宽度是高度的整数倍，允许这样切割
							const tileSize = Math.floor(width / 3);
							const canvasId = 'myCanvas';
							let base64Images = [];
							let promiseChain = Promise.resolve();

							// 创建一个canvas context
							const context = wx.createCanvasContext(canvasId);

							for (let row = 0; row < 3; row++) {
								for (let col = 0; col < 3; col++) {
									// 对于9宫格的每一个格子，都进行绘制和裁剪
									promiseChain = promiseChain.then(() => {
										return new Promise((innerResolve, innerReject) => {
											// 清除canvas上的内容，以避免重叠绘制
											context.clearRect(0, 0, tileSize * 3,
												tileSize * 3);

											// 绘制图片的一部分到canvas上
											context.drawImage(imageUrl, col * tileSize,
												row * tileSize, tileSize, tileSize,
												0, 0, tileSize, tileSize);
											context.draw(false, () => {
												// 将canvas的内容转换为base64
												wx.canvasToTempFilePath({
													canvasId: canvasId,
													x: 0,
													y: 0,
													width: tileSize,
													height: tileSize,
													destWidth: tileSize,
													destHeight: tileSize,
													quality: 1, // 可选，设置导出图片的质量，1表示最高质量
													success: (
														result
													) => {
														wx.getFileSystemManager()
															.readFile({
																filePath: result
																	.tempFilePath,
																encoding: 'base64',
																success: (
																	data
																) => {
																	base64Images
																		.push(
																			'data:image/png;base64,' +
																			data
																			.data
																		);
																	innerResolve
																		(); // 当前格子处理完成
																},
																fail: innerReject // 读取文件失败
															});
													},
													fail: innerReject // canvasToTempFilePath失败
												});
											});
										});
									});
								}
							}

							// 所有格子处理完成后，更新页面数据并返回base64图片数组
							promiseChain.then(() => {
								// this.setData({ imgsrc: base64Images });
								this.imgsrc = base64Images
								resolve(base64Images);
							}).catch((error) => {
								console.error("处理图像时发生错误：", error);
								reject(error);
							});
						},
						fail: (error) => {
							console.error("加载图像失败：", error);
							reject(error);
						}
					});
				});
			},

			onSaveAll() {
				this.imgsrc.forEach((item, index) => {
					const link = document.createElement('a');
					link.style.display = 'none'; // 隐藏链接
					link.href = item; // 将Base64字符串设置为下载链接
					link.download = `image${index}.png`; // 设置下载文件名

					// 将a元素添加到文档中，并模拟点击
					document.body.appendChild(link);
					link.click();

					// 移除a元素
					document.body.removeChild(link);
				})
			},
			onSaveAllwx() {
				console.log(this.imgsrc)
				const fs = wx.getFileSystemManager();
				const tempFilePaths = []; // 用于存储临时文件路径的数组

				// 假设imgSrc是包含Base64编码图片的数组
				this.imgsrc.forEach((base64, index) => {
					const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
					if (!format) {
						return console.error('ERROR_BASE64_PARSE');
					}
					const timeStamp = new Date().getTime();
					const tempFilePath = `${wx.env.USER_DATA_PATH}/tmp_base64_${timeStamp}_${index}.${format}`;

					// 将Base64数据写入临时文件
					const buffer = wx.base64ToArrayBuffer(bodyData);
					// fs.writeFileSync({
					// 	filePath: tempFilePath,
					// 	data: buffer,
					// 	encoding: 'binary',
					// 	success: () => {
					// 		tempFilePaths.push(tempFilePath);
					// 		// 这里可以添加逻辑来处理每个临时文件，比如预览或上传
					// 		console.log(`Temp file saved at ${tempFilePath}`);
					// 		// 如果需要，可以在这里调用保存图片到相册的函数，但注意每次只能保存一张
					// 		this.saveImageToAlbum(tempFilePath, index);
					// 	},
					// 	fail: err => {
					// 		console.error(`Failed to save temp file: ${err}`);
					// 	}
					// });
					try {
					    // 使用 writeFileSync 方法来同步写入文件
					    fs.writeFileSync(tempFilePath, buffer);
					    
					    // 写入成功后，添加文件路径到 tempFilePaths 数组
					    tempFilePaths.push(tempFilePath);
					    
					    // 这里可以添加逻辑来处理每个临时文件，比如预览或上传
					    console.log(`Temp file saved at ${tempFilePath}`);
					    
					    // 如果需要，可以在这里调用保存图片到相册的函数，但注意每次只能保存一张
					    this.saveImageToAlbum(tempFilePath, index);
					} catch (err) {
					    // 捕获并处理写入文件时的错误
					    console.error(`Failed to save temp file: ${err}`);
					}
				});
			},
			addressAgain() {
				wx.openSetting({
					success(res) {
						console.log(res.authSetting)
						// res.authSetting = {
						//   "scope.userInfo": true,
						//   "scope.userLocation": true
						// }
					}
				})
			},


			saveImageToAlbum(filePath, index) {

				wx.getSetting({
					success: (res) => {
						if (res.authSetting.hasOwnProperty('scope.writePhotosAlbum') === false) {
							wx.showToast({
								title: "请手动获取相册权限"
							})
						} else {
							setTimeout(()=>{
								wx.saveImageToPhotosAlbum({
									filePath: filePath,
									success:(res)=> {
										this.currentLength.push(Number(index))
										if(this.currentLength&&this.currentLength.length===9){
											wx.showToast({
												title:'全部已保存'
											})
										}
										console.log('Image saved to album', res);
									},
									fail:(err)=> {
										console.error('Failed to save image to album',
											err);
									}
								});
							},1000)
							
						}
					}

				})



			}

		}

	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
